/*
	Flie:						CSpriteAnimatorFireball.cpp
	Course:				SGD 1207
	Author:				Kori Po
	Purpose:			Run fireball attack animation
*/

#include "SpriteAnimatorFireball.h"

CSpriteAnimatorFireball::CSpriteAnimatorFireball(void)
{
	m_TextureGuy = nullptr;
	m_TextureGuy = CSGD_TextureManager::GetInstance();

	m_nFrameWidth = 60;
	m_nFrameHeight = 64;
	
	m_nNumCols = 14;
	m_nNumRows = 1;

	m_nCurFrame = 0;
	m_nMaxFrames = 8;

	m_bIsPlaying = true;
	m_bIsLooping = true;

	m_fSpeed = 1.0f;

	m_fTimePerFrame = 0.1f;
	m_fTimeWaited = 10;

	m_nImageID = m_TextureGuy->LoadTexture(_T("Resource/Graphics/Sprites/Abilities/KP_Fireball.png"), D3DCOLOR_XRGB(255,255,255));
}


CSpriteAnimatorFireball::~CSpriteAnimatorFireball(void)
{
	m_TextureGuy->UnloadTexture(m_nImageID);
	m_TextureGuy = nullptr;
}

void CSpriteAnimatorFireball::Update( float fElapsedTime )
{
	// Are we playing the animation?
	if( m_bIsPlaying == false )
		return;


	// Increase the timer
	m_fTimeWaited += fElapsedTime * m_fSpeed;

	// Move to next frame?
	if( m_fTimeWaited > m_fTimePerFrame )
	{
		m_nCurFrame++;
		m_fTimeWaited = 0.0f;


		// Reached the end of the animation?
		if( m_nCurFrame >= m_nMaxFrames )
		{
			// Restart?
			if( m_bIsLooping == true )
				m_nCurFrame = 0;
			else
			{
				m_nCurFrame = m_nMaxFrames-1;
				m_bIsPlaying = false;
			}
		}
	}
}

void CSpriteAnimatorFireball::Render( int nX, int nY, float fScale = 1.0f, float fRotation = 0.0f,  DWORD dwColor = -1UL )
{
	// Get source rect
	RECT rSource = CellAlgorithm( m_nCurFrame );

	// Draw!
	m_TextureGuy->Draw( m_nImageID, nX, nY, fScale, fScale, &rSource, 
				0.0f, 0.0f, fRotation, dwColor );
}

// Animation Controls:
void CSpriteAnimatorFireball::Play( bool bLoop = true, float fSpeed = 1.0f )
{
	m_nCurFrame = 0;
	m_fTimeWaited = 0.0f;

	m_fSpeed = fSpeed;
	m_bIsLooping = bLoop;
	m_bIsPlaying = true;
}

void CSpriteAnimatorFireball::Stop( void )			// pause
{
	m_bIsPlaying = false;
}

void CSpriteAnimatorFireball::Resume( void )			// unpause
{
	m_bIsPlaying = true;
}

RECT CSpriteAnimatorFireball::CellAlgorithm( int id )
{
	assert( id >= 0 && id < m_nNumCols*m_nNumRows );

	RECT rSource = { };

	rSource.left = (id % m_nNumCols) * m_nFrameWidth;
	rSource.top = ((id /m_nNumCols) * m_nFrameHeight);

	rSource.right = rSource.left + m_nFrameWidth;
	rSource.bottom = rSource.top + m_nFrameHeight;

	return rSource;
}